# name: external_user_sync
# about: Sync user data to an external platform upon registration
# version: 0.1
# authors: delong1998

enabled_site_setting :external_user_sync_enabled

after_initialize do
  # Load the necessary Discourse modules
  require_dependency 'user'

  # Define the event listener
  on(:user_created) do |user|
    sync_user_to_external_platform(user)
  end

  def sync_user_to_external_platform(user)
    return unless SiteSetting.external_user_sync_enabled

    require 'net/http'
    require 'uri'
    require 'json'

    # Prepare the request
    uri = URI.parse(SiteSetting.external_user_sync_api_endpoint)
    http = Net::HTTP.new(uri.host, uri.port)
    http.use_ssl = true if uri.scheme == 'https'

    request = Net::HTTP::Post.new(uri.request_uri, 'Content-Type' => 'application/json')
    request.body = {
      username: user.username,
      email: user.email,
      password: user.password, # Note: Discourse does not store plain text passwords，
      nickname: user.name,
      validateCode: SiteSetting.external_user_sync_validate_code,
    }.to_json

    # Send the request
    response = http.request(request)

    # Log the response for debugging
    Rails.logger.info("External user sync response: #{response.body}")
  rescue => e
    Rails.logger.error("Failed to sync user to external platform: #{e.message}")
  end
end
